<?php

namespace App\Http\Controllers\Platform;

use Exception;
use Carbon\Carbon;
use App\Models\Company;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\System\SysLog;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Events\Company\AcceptedEvent;
use App\Repositories\CompanyRepository;
use App\Http\Requests\Platform\Company\VettingRequest;
use App\Http\Requests\Platform\Company\DestroyResource;
use App\Http\Requests\Platform\Company\BatchVettingRequest;

/**
 * 公司管理逻辑控制器
 *
 * Date: 07/05/2018
 * @author George
 * @package App\Http\Controllers\Platform
 */
class CompanyController extends Controller
{
	protected $userRepository;
	protected $companyRepository;

	/**
	 * CompanyController constructor.
	 * @param CompanyRepository $companyRepository
	 */
	public function __construct(
		CompanyRepository $companyRepository
	)
	{
		$this->companyRepository = $companyRepository;
	}

	/**
	 * 获取企业信息
	 *
	 * Date: 07/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function all(Request $request)
	{
		$title = $request->get('title');
		$city = $request->get('city');
		$legal = $request->get('legal');
		$approver_id = $request->get('approver_id');
		$paginate = $request->get('paginate', 15);

		$query = DB::table('companies')
			->select(['companies.id', 'title', 'city', 'legal', 'admins.name as approver'])
			->leftJoin('audits', 'companies.id', '=', 'audits.auditable_id')
			->leftJoin('admins', 'audits.approver_id', '=', 'admins.id')
			->where('auditable_type', 'company')
			->where('companies.status', '=', 'accepted')
			->whereNull('deleted_at');

		if ($title) {
			$query->where('companies.title', 'like', "%{$title}%");
		}

		if ($city) {
			$query->where('companies.city','like', "%{$city}%");
		}

		if ($legal) {
			$query->where('companies.legal', 'like', "%{$legal}%");
		}

		if ($approver_id) {
			$query->where('admins.id', $approver_id);
		}

		return success($query->paginate($paginate));
	}

	/**
	 * 获取待审核公司信息
	 *
	 * Date: 2018/5/28
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function unapproved(Request $request)
	{
		$title = $request->get('title');
		$city = $request->get('city');
		$legal = $request->get('legal');
		$paginate = $request->get('paginate', 15);
		$query = Company::query();

		if ($title) {
			$query->where('title', 'like', "%{$title}%");
		}

		if ($city) {
			$query->where('city','like', "%{$city}%");
		}

		if ($legal) {
			$query->where('legal', 'like', "%{$legal}%");
		}

		$query->where('status', 'pending');
		return success($query->paginate($paginate));
	}

	/**
	 * 获取公司详情
	 *
	 * Date: 07/05/2018
	 * @author George
	 * @param Company $company
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function details(Company $company)
	{
		$user = $company->creator()->first();
		$company->account = $user ? $user->mobile : '未找到创建人';
		return success($company);
	}

	/**
	 * 删除公司
	 *
	 * Date: 07/05/2018
	 * @author George
	 * @param DestroyResource $request
	 * @param Company $company
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
	public function destroy(DestroyResource $request, Company $company)
	{
		$company->delete();
        SysLog::log(Auth::user(),'公司管理模块','删除公司');
		return deleted();
	}

	/**
	 * 处理审核
	 *
	 * Date: 24/04/2018
	 * @author George
	 * @param VettingRequest $request
	 * @param $company
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Throwable
	 */
	public function vetting(VettingRequest $request, $company)
	{
		$attributes = $this->extractInputFromRules($request, $request->rules());

		try {
			DB::beginTransaction();
			/**
			 * @var Company $company
			 */
			$company = Company::findOrFail($company);
			$company->status = $attributes['status'];
			$company->saveOrFail();
			// 创建审核记录
			DB::table('audits')->insert([
				'auditable_id' => $company->id,
				'auditable_type' => 'company',
				'proposer' => $company->creator_id,
				'company_id' => $company->id,
				'approver_id' => Auth::id(),
				'approver_type' => Str::snake(class_basename(Auth::user())),
				'status' => $attributes['status'],
				'comment' => array_get($attributes, 'comment'),
				'created_at' => Carbon::now(),
				'updated_at' => Carbon::now()
			]);

			if ($attributes['status'] === 'rejected') {
				DB::table('users')->where('id', $company->creator_id)->update(['company_id' => 0]);
			} elseif ($attributes['status'] === 'accepted') {
				// 更新用户权限
				DB::table('users')->where('id', $company->creator_id)->update(['manager' => 1]);
				// 创建公司和用户关联关系
				DB::table('company_user_pivot')->insert([
					'company_id' => $company->id,
					'user_id' => $company->creator_id,
					'hiredate_at' => date('Y-m-d H:i:s'),
				]);
			}
			DB::commit();

			if ($attributes['status'] === 'accepted') {
				// 分发事件
				event(new AcceptedEvent($company));
			}
            SysLog::log(Auth::user(),'公司管理模块','审核公司');
            return success([]);
		} catch (Exception $exception) {
			DB::rollBack();
			Log::error($exception);
			return failed('审批处理失败');
		}
	}

	/**
	 * 批量通过
	 *
	 * Date: 24/04/2018
	 * @author George
	 * @param BatchVettingRequest $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Throwable
	 */
	public function batchVetting(BatchVettingRequest $request)
	{
		$ids = $request->get('ids');
		$user = Auth::user();

		try {
			DB::beginTransaction();
			$companies = Company::query()->whereIn('id', $ids)->get();
			$records = [];
			$company_user_pivot = [];
			foreach ($companies as $company) {
				$records[] = [
					'auditable_id' => $company->id,
					'auditable_type' => 'company',
					'proposer' => $company->creator_id,
					'company_id' => $company->id,
					'approver_id' => Auth::id(),
					'approver_type' => Str::snake(class_basename($user)),
					'status' => 'accepted',
					'comment' => null,
					'created_at' => Carbon::now(),
					'updated_at' => Carbon::now()
				];
				$company_user_pivot[] = [
					'company_id' => $company->id,
					'user_id' => $company->creator_id,
					'hiredate_at' => date('Y-m-d H:i:s'),
				];
			}
			DB::table('audits')->insert($records);
			// 更新创建人权限
			DB::table('users')->whereIn('id', $companies->pluck('creator_id'))->update(['manager' => 1]);
			// 创建公司和人员关系
			DB::table('company_user_pivot')->insert($company_user_pivot);
			DB::commit();

			foreach ($companies as $company) {
				event(new AcceptedEvent($company));
			}
            SysLog::log(Auth::user(),'公司管理模块','批量审核公司');
            return success($ids);
		} catch (Exception $exception) {
			DB::rollBack();
			Log::error($exception);
			return internalError('审核提交失败');
		}
	}
}
